package com.wxf.Topics;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * topic模式消费者消费消息的第一种写法
 */
public class Consumer01 {
    public static void main(String[] args) {
        // 1-创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.127.131");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        connectionFactory.setVirtualHost("/");
        // 2-创建连接
        Connection conn = null;
        Channel channel = null;
        try {
            conn = connectionFactory.newConnection("消费者01");

            // 3-创建通道
            channel = conn.createChannel();

            // 参数1：队列名称
            // 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认
            channel.basicConsume(Producer.TOPIC_QUEUE_ALL, true,"",false,false,null, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    // 消息可以通过delivery.getBody()获取，不过此时获取的是字节，需要转成字符
                    System.out.println("message received:"+new String(delivery.getBody(),"utf-8"));
                }
            },new CancelCallback(){
                // 如果消费失败，做相应处理
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("massage received fail");
                }
            });
            // 阻断程序，用于观察过程
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            //7-关闭通道
            if(channel!=null&&channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            // 8-关闭连接
            if(conn!=null&&conn.isOpen()){
                try {
                    conn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
